import zlib
import pikepdf
from pikepdf import Name, PdfImage

# input_file = r"C:\Users\yang.lei\Downloads\Origin-comparative  Isosorbide-2021.pdf"
# output_file = r"C:\Users\yang.lei\Downloads\out.pdf"

input_file = r"D:\dl\Origin-comparative  Isosorbide-2021.pdf"
output_file = r"D:\dl\out.pdf"

my_pdf = pikepdf.Pdf.open(input_file)

# new_image.Filter = "/FlateDecode"
# new_image.Type = "/XObject"
# new_image.Subtype = "/Image"
# new_image.Interpolate =False
# new_image.ColorSpace ="/DeviceRGB"
cnt = 0
for page in my_pdf.pages:
    cnt += 1
    # for page in my_pdf.pages[:1]:
    # for page in [my_pdf.pages[-1]]:
    #     print(repr(page))
    # # print(len(page.Contents))
    # print(repr(page.Contents[9]))
    #

    if cnt == 12:
        instructions = pikepdf.parse_content_stream(page.Contents[9])
        # print(instructions)
        data = pikepdf.unparse_content_stream(instructions)
        # print(len(data))
        page.Contents[9] = my_pdf.make_stream(data=data[:120000])
        try:
            new_image = my_pdf.make_stream(b'\xff')
            new_image.Width, new_image.Height = 1, 1
            new_image.BitsPerComponent = 1
            new_image.ImageMask = True
            new_image.Subtype = Name("/Image")
            new_image.Type = Name("/XObject")
            new_image.Decode = [0, 1]
            page.Resources.XObject['/Image2'] = new_image
            # del page.Resources.XObject['/Image5']
        except Exception as e:
            print(e)
    # print(data.decode('utf-8'))
    # data = pikepdf.unparse_content_stream(page.Contents[9])
    # with open(r"D:\dl\p9",'wb') as f:
    #     f.write(data)
    #     print('================')
    # print(data.decode('ascii'))
    # del page.Contents[9]
    # del page.Contents[3]
    # del page.Contents[2]
    # del page.Contents[4]
    # for image_name, rawimage in page.images.items():
    #     if image_name == '/Image5':
    if cnt == 1:
        try:
            new_image = my_pdf.make_stream(b'\xff')
            new_image.Width, new_image.Height = 1, 1
            new_image.BitsPerComponent = 1
            new_image.ImageMask = True
            new_image.Subtype = Name("/Image")
            new_image.Type = Name("/XObject")
            new_image.Decode = [0, 1]
            page.Resources.XObject['/Image1'] = new_image
            # del page.Resources.XObject['/Image5']
        except Exception as e:
            print(e)

my_pdf.save(output_file)
